// index.js
// 获取应用实例
const app = getApp()
const {http} = require('../../utils/util')  //请求接口封装

Page({
  data: {
    orderNo:'',
    orderState:-1,
    wxPayData:''
  },
  onLoad(e) {
    const scene = getApp().globalData.scene
    if(scene !== 1069){
      wx.showToast({
        title: '暂不支持',
        icon: 'error',
        duration: 2000,
        complete:()=>{
          // wx.navigateBack({delta: 1})
        }
      })
      
      return;
    }
    console.log(e)
    this.data.orderNo = e.orderNo;
    this.data.ordeAmt = e.ordeAmt;
    this.order2Pay()
  },
  launchAppError(e){

  },
  next(){
    if(this.data.orderState==1){ //支付完成

    }else if(this.data.orderState == 0){ //支付取消
      this.order2Pay()
    }else{ //支付失败 or 处理中

    }
  },
  // 事件处理函数
  order2Pay(){
    const that = this
    wx.login({
      success: res => {
        http('POST','https://test.pay.zj.cn/bmp/temp/queryOpenId',//获取openid
        {code:res.code},
        function(res){
          var openid = res.data.data
          http('POST','https://test.pay.zj.cn/bmp/temp/pay',//支付下单
          {openid:openid},
          function(res){
            var payData = JSON.parse(res.data.data)//获取微信支付所需参数
            wx.requestPayment({//拉起微信支付
              timeStamp: payData.timeStamp,
              nonceStr: payData.nonceStr,
              package: payData.package,
              signType: payData.signType,
              paySign: payData.paySign,
              success (res) { //支付成功回调
                res.payState = 1;
                res.orderNo = that.data.orderNo;
                that.setData({
                  wxPayData:JSON.stringify(res),
                  orderState:1
                })
              },
              fail (res) { //支付失败回调
                res.payState = 2;
                res.orderNo = that.data.orderNo;
                that.setData({
                  wxPayData:JSON.stringify(res),
                  orderState:2
                })
              },
              complete(res){//支付结束回调（成功失败都会执行）
                console.log('complete',res)
                const errMsg = res.errMsg;
                if(errMsg && errMsg.indexOf('cancel')>-1){
                  res.orderNo = that.data.orderNo;
                  that.setData({
                    wxPayData:JSON.stringify(res),
                    orderState:0
                  })
                }
              }
            })
          })
        })
      }
    })
  },
})
